package com.miniserver.tql.database.impl;

import java.util.ArrayList;

import com.miniserver.tql.database.EngineContext;
import com.miniserver.tql.database.model.TAttr;
import com.miniserver.tql.database.model.TNode;

public class Binder {
	private String sql;
	private ArrayList<String> parameters = new ArrayList<String>();

	public String getSql() {
		return this.sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public ArrayList<String> getParams() {
		return this.parameters;
	}

	public static String paramValue(EngineContext context, String expr) {
		if (expr.startsWith("@") || expr.startsWith("?")) {
			int pos = expr.indexOf(':');
			if (pos > 0) {
				expr = expr.substring(pos + 1);
				return context.getFunction().eval(context, expr);
			} else {
				return context.get(expr, "NULL");
			}
		} else {
			return context.getFunction().eval(context, expr);
		}
	}

	public static boolean paramExists(EngineContext context, String expr) {
		String var = expr;
		if (var.startsWith("@") || var.startsWith("?")) {
			int pos = var.indexOf(':');
			if (pos > 0) {
				var = var.substring(0, pos);
			}
			//
			return context.contains(var);
		} else {
			return true;
		}
	}

	public static String applyReplace(EngineContext context, TNode tNode, String sql) {
		TAttr tReplace = tNode.getAttribute("replace");
		if (tReplace == null) {
			return sql;
		}
		//
		String[] replaces = tReplace.getValue().split(";");
		for (String s : replaces) {
			String name, value;
			// SQL中的replace占位符必须以@或?开头
			if (!s.startsWith("@") && !s.startsWith("?")) {
				continue;
			}
			//
			int pos = s.indexOf(':');
			if (pos > 0) {
				name = s.substring(0, pos);
				value = context.getFunction().eval(context, s.substring(pos + 1));
			} else {
				name = s;
				value = context.get(s, "NULL");
			}
			if (name.startsWith("?")) {
				name = "\\".concat(name);
			}
			sql = sql.replaceAll(name, value);
		}
		return sql;
	}

	public static String replaceNullCols(EngineContext context, TNode tNode, String sql, Binder binder) {
		TAttr isNullCol = tNode.getAttribute("isNullCol");
		if (isNullCol != null) {
			String isNullColValue = isNullCol.getValue();
			String[] colArray = isNullColValue.split(";");
			for (String col : colArray) {
				String colName = col.split(":")[0];
				String colValue = col.split(":")[1];
				String value = Binder.paramValue(context, colValue);
				if (value.equals("") || value.equals("NULL")) {
					sql = sql.replace(colName + "=?", colName + " is null ");
					binder.getParams().remove(colValue);
				}
			}
		}
		return sql;
	}
}
